import React, {Component} from 'react';
import {Button, Form, Input, Modal, Select, Space} from 'antd';
import {
    apiEditCourierInformation,
    apiReassignDeliveryman,
    apiSendOrders,
    apiShopOrderDetail,
} from '@/request/orderManagement'
import TheDialog from '@/components/TheDialog'
import StockOutModal from "./stockOutModal";
import Logistics from "./logistics";
import SelfLogistics from "./selfLogistics";

const {confirm} = Modal
export default class SendGoods extends Component {
    constructor(props) {
        super(props)
        this.formRef = React.createRef()
        this.stockOutModalRef = React.createRef()
        this.logisticsRef = React.createRef()
        this.selfLogisticsRef = React.createRef()
        this.state = {
            loading: false,
            visible: false,
            orderId: '',
            off: "0",
            courierOrDelivery: "0",
            title: "发货",
            footer: false,
            isMultiPackage: false, // 是否多包裹
            oneCode: null // 单包裹code
        }
    }

    componentDidMount() {
    }

    closeDialog = () => {
        this.setState({
            visible: false,
            // orderId: '',
            off: "0",
            courierOrDelivery: "0"
        })
    }
    saveDialog = (value) => {
        const {orderId, isMultiPackage, oneCode} = this.state
        if (value.courierNo) {
            value.courierNo = value.courierNo.trim()
        }
        if (isMultiPackage) {
            value.code = this.stockOutModalRef.current.getCkCode()
        }
        if (oneCode) {
            value.code = oneCode
        }
        this.setState({
            loading: true
        }, async () => {
            if (this.state.courierOrDelivery === "1") {
                // 修改自配送
                let res = await apiReassignDeliveryman({orderId, ...value})
                if (res.code === 0) {
                    React.$message({
                        type: "info",
                        content: '修改成功'
                    })
                    this.closeDialog()
                    this.props.refresh()
                    if (isMultiPackage) {
                        this.stockOutModalRef.current.close()
                    }
                }
                this.setState({
                    loading: false
                })
            } else if (this.state.courierOrDelivery === "2") {
                // 修改快递
                let res = await apiEditCourierInformation({orderId, ...value})
                if (res.code === 0) {
                    React.$message({
                        type: "info",
                        content: '修改成功'
                    })
                    this.closeDialog()
                    this.props.refresh()
                    if (isMultiPackage) {
                        this.stockOutModalRef.current.close()
                    }
                }
                this.setState({
                    loading: false
                })
            } else {
                // 发货
                let res = await apiSendOrders({orderId, ...value})
                if (res.code === 0) {
                    React.$message({
                        type: "info",
                        content: '发货成功'
                    })
                    this.closeDialog()
                    this.props.refresh()
                    if (isMultiPackage) {
                        this.stockOutModalRef.current.close()
                    }
                }
                this.setState({
                    loading: false
                })
            }

        })
    }
    open = async (orderId, type, orderState) => {
        let arr = []
        switch (type) {
            case 'send': // 发货
                arr = [
                    <Button key="send" type="primary" onClick={() => this.send(orderId)}>
                        发货
                    </Button>,
                    <Button key="cancel" onClick={this.stockOutModalRef.current.handleCancel}>
                        取消
                    </Button>,
                ]
                break;
            // case 'delivery': // 修改配送员
            //     arr = [
            //         <Button key="view" onClick={()=>this.viewLogistics('delivery')}>
            //             查看物流
            //         </Button>,
            //         <Button key="delivery" onClick={()=>this.send(orderId)}>
            //             修改配送员
            //         </Button>
            //     ]
            //     break;
            case 'courier': // 修改快递
                arr = [
                    <Button key="view" onClick={() => this.viewLogistics()}>
                        查看物流
                    </Button>,
                    <Button key="courier" onClick={() => this.send(orderId)}>
                        修改快递
                    </Button>
                ]
                break;
            case 'stockOutPrint': // 出库单打印
                arr = [
                    <Button key="view" onClick={() => this.props.stockOutPrint(orderId)}>
                        出库单打印
                    </Button>
                ]
                break;
        }
        this.setState({
            orderId,
            footer: arr,
            isMultiPackage: true
        }, () => {
            this.stockOutModalRef.current.open(orderId, type, orderState)
        })
    }
    viewLogistics = () => {
        const {orderId} = this.state;
        const code = this.stockOutModalRef.current.getCkCode();
        const type = this.stockOutModalRef.current.getCourier();
        switch (type) {
            case 'courier': // 快递物流
                this.logisticsRef.current.onLogistics(orderId, code)
                break;
            case 'delivery': // 自配送物流
                this.selfLogisticsRef.current.openModal(orderId, code)
                break;
        }
    }
    send = async (orderId, code) => {
        let that = this
        if (code) {
            this.setState({
                oneCode: code
            })
        } else {
            this.setState({
                oneCode: null
            })
        }
        // 查询订单是否存在退货商品
        let hasReturn = await apiShopOrderDetail({orderId})
        if (hasReturn.code === 0 && hasReturn.data) {
            let flag = hasReturn.data.orderDetailList.filter(item => !['4', '0', null].includes(item.salesStatus))
            if (flag.length > 0) {
                confirm({
                    title: '提示', content: <div style={{color: 'red'}}>订单异常:存在退款商品，是否继续操作？</div>,
                    onOk() {
                        that.defaultOrderEcho(hasReturn.data, orderId)
                    },
                    onCancel() {
                    },
                });
                return
            }
            that.defaultOrderEcho(hasReturn.data, orderId)
        }
    }
    defaultOrderEcho = (data, orderId) => {
        this.setState({
            visible: true,
            orderId,
            title: "发货"
        }, () => {
            // 多包裹维度获取快递信息
            let { isMultiPackage } = this.state;
            if (isMultiPackage){
                data = this.stockOutModalRef.current.getCkInfo()
                // data.deliveryTask = {
                //     deliverymanId: data.deliverymanId
                // }
            }
            if (data.courierNo) {
                this.setState({
                    courierOrDelivery: "2",
                    off: "1",
                    title: "修改快递"
                }, () => {
                    this.formRef.current.setFieldsValue({
                        "courierCode": data.courierCode,
                        "courierNo": data.courierNo
                    })
                })
            }
            if (data.deliveryTask) {
                this.setState({
                    courierOrDelivery: "1",
                    off: "2",
                    title: "修改配送员"
                }, () => {
                    this.formRef.current.setFieldsValue({
                        "courierCode": data.courierCode,
                        "deliverymanId": data.deliveryTask.deliverymanId
                    })
                })
            }
        })
    }
    courierChange = (e) => {
        // console.log(e)
        if (e === "HQM") {
            this.setState({
                off: "2"
            })
        } else {
            this.setState({
                off: "1"
            })
        }
    }

    render() {
        const {visible, loading, off, courierOrDelivery, title, footer} = this.state
        const {options, courierOptions} = this.props
        return (
            <>
                <StockOutModal
                    courierList={options}
                    history={this.props.history}
                    ref={this.stockOutModalRef}
                    footer={footer}
                />
                <Logistics
                    options={options}
                    ref={this.logisticsRef}
                />
                <SelfLogistics
                    ref={this.selfLogisticsRef}
                />
                <TheDialog
                    visible={visible}
                    title={title}
                    width={400}
                    handleCancel={this.closeDialog}
                    footer={null}
                >
                    <Form ref={this.formRef} onFinish={this.saveDialog} labelCol={{span: 7}} wrapperCol={{span: 15}}>
                        <Form.Item label="快递公司" name="courierCode" rules={[{required: true}]}>
                            <Select allowClear
                                    options={
                                        options.filter((v) => {
                                            if (courierOrDelivery === "1") {
                                                return v.value === 'HQM'
                                            } else if (courierOrDelivery === "2") {
                                                return v.value !== 'HQM'
                                            } else {
                                                return v.value
                                            }
                                        })
                                    }
                                    showSearch
                                    filterOption={(input, option) => {
                                        return option.label.toUpperCase().includes(input.toUpperCase())
                                    }}
                                    onChange={this.courierChange}
                                    placeholder='请选择快递公司'/>
                        </Form.Item>
                        {off === '1' ? <Form.Item label="单号" name="courierNo" rules={[{required: true}]}>
                            <Input placeholder='请输入单号'/>
                        </Form.Item> : []}
                        {off === '2' ? <Form.Item label="配送员" name="deliverymanId" rules={[{required: true}]}>
                            <Select allowClear
                                    options={courierOptions}
                                    showSearch
                                    filterOption={(input, option) => {
                                        return option.label.toUpperCase().includes(input.toUpperCase())
                                    }}
                                // onChange={this.courierManChange}
                                    placeholder='请选择配送员'/>
                        </Form.Item> : []}
                        <Form.Item wrapperCol={{offset: 7, span: 15,}}>
                            <div style={{display: 'flex', justifyContent: 'flex-end'}}>
                                <Space>
                                    <Button onClick={this.closeDialog}>取消</Button>
                                    <Button type="primary" htmlType='submit' loading={loading}>确认</Button>
                                </Space>
                            </div>
                        </Form.Item>
                    </Form>
                </TheDialog>
            </>
        );
    }
}
